import 'dart:convert';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:fake_handwriting/Util.dart';
import 'package:fake_handwriting/generated/l10n.dart';
import 'package:fake_handwriting/http/bean/master_bean.dart';
import 'package:fake_handwriting/http/http.dart';
import 'package:flutter/material.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_preview/image_preview.dart';
class Master extends StatefulWidget {
  const Master({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => MasterPage();
}

class MasterPage extends State<Master> {
  List<MasterBean?> list=[];
  List<CancelToken>tokens=[];
  @override
  void initState() {
    super.initState();
    init();
  }
  @override
  void dispose() {
    for (var element in tokens) {
      element.cancel();
    }
    super.dispose();
  }
  @override
  Widget build(BuildContext context){
    return Scaffold(
      body:SafeArea(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20,vertical: 20),
          child: GridView.builder(
              shrinkWrap: true,
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount:3,
                  crossAxisSpacing:5,
                  mainAxisSpacing:5,
                  childAspectRatio:1),
              itemCount: list.length,
              itemBuilder: (BuildContext context, int index) {
                List paths=json.decode(list[index]!.path.toString());
                List<String> l=[];
                for (var element in paths) {
                  l.add(Http.BASE_URL+element.toString());
                }
                return InkWell(
                  onTap:(){
                    openImagesPage(
                      Navigator.of(context),
                      imgUrls: l,
                      index: 0,
                    );
                  },
                  onLongPress:() async {
                    var res = await showDialog(context: context, builder: (context) => SimpleDialog(
                          title: Text(S.of(context).selectAction),
                          children:[
                            SimpleDialogOption(
                              child: Text((list[index]!.visible!)?S.of(context).hide:S.of(context).open),
                              onPressed: () {
                                Navigator.pop(context,(list[index]!.visible!)?S.of(context).hide:S.of(context).open);
                              },
                            ),
                            const Divider(),
                            SimpleDialogOption(
                              child:Text(S.of(context).saveToLocal),
                              onPressed: () {
                                Navigator.pop(context,S.of(context).saveToLocal);
                              },
                            ),
                            const Divider(),
                            SimpleDialogOption(
                              child:Text(S.of(context).delete),
                              onPressed: () async {
                                Navigator.pop(context, S.of(context).delete);
                              },
                            ),
                          ],
                        ));
                    if(res==S.of(context).delete){
                      await Http.delete_master(list[index]!.id!);
                      init();
                    }
                    if(res==S.of(context).open){
                      await Http.master_visible(list[index]!.id!,"0");
                      init();
                    }
                    if(res==S.of(context).hide){
                      await Http.master_visible(list[index]!.id!,"1");
                      init();
                    }
                    if(res==S.of(context).saveToLocal){
                      if(await Util.checkPermission(context)){
                        List paths=json.decode(list[index]!.path.toString());
                        paths.forEach((element) async {
                          CancelToken token=CancelToken();
                          tokens.add(token);
                          var response = await Dio().get(Http.BASE_URL+element.toString(), options: Options(responseType: ResponseType.bytes),cancelToken: token);
                          await ImageGallerySaver.saveImage(Uint8List.fromList(response.data), quality: 100, name:"${DateTime.now().millisecondsSinceEpoch}.png");
                        });
                        Util.toast(S.of(context).saveSucceed);
                      }
                    }
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.blue),image: DecorationImage(
                      image: NetworkImage(Http.BASE_URL+paths[0]),fit: BoxFit.cover
                    )
                    ),
                    child: Column(children: [
                      Text(list[index]!.title.toString(),maxLines: 1,overflow:TextOverflow.ellipsis ,style: const TextStyle(
                        fontWeight: FontWeight.w600
                      ),),
                      Container(
                        decoration: const BoxDecoration(
                            color: Colors.black
                        ),
                        child: list[index]!.visible!?Row(children: [
                          const Icon(Icons.visibility,color: Colors.white,),
                          Text(S.of(context).visibleToOthers,style: const TextStyle(
                              color: Colors.white
                          ),)
                        ],):Row(children: [
                          const Icon(Icons.visibility_off,color: Colors.white,),
                          Text(S.of(context).invisibleToOthers,style: const TextStyle(
                              color: Colors.white
                          ),)
                        ],),
                      )
                    ],mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.start,),
                  ),
                );
              }),
        ),
      ),
      appBar: AppBar(
        title:Text(S.of(context).myCreation),
      ),
    );
  }
  Future<void> init() async {
    list=(await Http.get_my_works())!;
    setState(() {});
  }
}